//
//  MNetworkItem.m
//  MobiProject
//
//  Created by 阔 李 on 15-3-25.
//  Copyright (c) 2015年 阔 李. All rights reserved.
//

#import "MNetworkItem.h"
#import "MNetworkHandler.h"
#import "AFNetworking.h"

@implementation MNetworkItem

- (MNetworkItem *) initWithtype:(NetWorkType) networkType
                             url:(NSString *) url
                          params:(NSDictionary *) params
                        delegate:(id) delegate
                       hashValue:(NSUInteger) hashValue
                         showHUD:(BOOL) showHUD
                    successBlock:(NWSuccessBlock) successBlock
                    failureBlock:(NWFailureBlock) failureBlock
{
    if (self = [super init]) 
    {
        self.networkType = networkType;
        self.url = url;
        self.params = params;
        self.delegate = delegate;
        self.hashValue = hashValue;
        self.showHUD = showHUD;
        
        
        __weak MNetworkItem *weekSelf = self;
        
        if (networkType == NetWorkGET) 
        {
            AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
         
            //传入json格式数据，不写则普通post
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
           
            /**
             *  请求队列的最大并发数
             */
            //    manager.operationQueue.maxConcurrentOperationCount = 5;
            /**
             *  请求超时的时间
             */
            manager.requestSerializer.timeoutInterval = API_TIME_OUT;
            
            [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
//                if (successBlock) {
//                    successBlock(responseObject);
//                }
                
                //NSURLRequest *currentRequest =task.currentRequest;
                
                NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

                // 如果是.net后台返回数据，并且json数据有xml包着的话，请释放这一句
                //responseString = [responseString ignoreDotNetSpecialString];
                
                // 如果返回值有html特殊字符，请释放这一句
                //responseString = [responseString ignoreHTMLSpecialString];
        
                NSString *str=@"https://m.mingpinduobao.com/index.php/member/cart/app_paysubmit";
                NSString *str1=@"https://m.mingpinduobao.com/index.php/mobile/cart/app_addmoney/";
                NSURLRequest *currentRequest =task.currentRequest;
                if ([currentRequest.URL.absoluteString rangeOfString:str].location != NSNotFound) {
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
                }
                if ([currentRequest.URL.absoluteString rangeOfString:str1].location != NSNotFound) {
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
                }
                
                // 自带json转换 (string -> json格式)
                if (responseString) {
                    id returnData = [NSJSONSerialization
                                     JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding]
                                     options:NSJSONReadingMutableContainers
                                     error:nil];
                    if (successBlock) {
                        successBlock(returnData);
                    }
                }else{
                    if (successBlock) {
                        successBlock(nil);
                    }
                }
                
                [[MNetworkHandler sharedInstance] removeItem:weekSelf];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                if (failureBlock) {
                    failureBlock(error);
                }
                
                [[MNetworkHandler sharedInstance] removeItem:weekSelf];
            }];
        } 
        else if (networkType == NetWorkPOST)
        {
            AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
            //传入json格式数据，不写则普通post
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            manager.requestSerializer.timeoutInterval = 60;
            manager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
            manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
//            manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/html",@"text/json",@"text/plain",@"text/javascript",@"text/xml",@"image/*"]];
            
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
           
            
            [manager POST:self.url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
                NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@",responseString);
                // 如果是.net后台返回数据，并且json数据有xml包着的话，请释放这一句
                //responseString = [responseString ignoreDotNetSpecialString];
                
                // 如果返回值有html特殊字符，请释放这一句
                //responseString = [responseString ignoreHTMLSpecialString];
                NSString *str=@"https://m.mingpinduobao.com/index.php/member/cart/app_paysubmit";
                NSString *str1=@"https://m.mingpinduobao.com/index.php/mobile/cart/app_addmoney/";
                NSURLRequest *currentRequest =task.currentRequest;
                if ([currentRequest.URL.absoluteString rangeOfString:str].location != NSNotFound) {
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
                }
                if ([currentRequest.URL.absoluteString rangeOfString:str1].location != NSNotFound) {
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
                    responseString = [responseString stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
                }

                
                
                // 自带json转换 (string -> json格式)
                if (responseString) {
                    id returnData = [NSJSONSerialization
                                     JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding]
                                     options:NSJSONReadingMutableContainers
                                     error:nil];
                    if (successBlock) {
                        successBlock(returnData);
                    }
                }else{
                    if (successBlock) {
                        successBlock(nil);
                    }
                }
                [[MNetworkHandler sharedInstance] removeItem:weekSelf];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failureBlock) {
                    failureBlock(error);
                }
                
                [[MNetworkHandler sharedInstance] removeItem:weekSelf];
            }];
        }
        [[MNetworkHandler sharedInstance] addItem:self];
    }
    
    return self;
}

@end
